package main

import (
	"fmt"
	"os"
	"sanguo/cluster"
	"sanguo/node/common/asynwrap"
	"sanguo/node/common/db"
	"sanguo/node/node_game"
	_ "sanguo/node/node_game/common"
	"sanguo/node/node_game/common/IDGen"
	_ "sanguo/node/node_game/module"
	_ "sanguo/node/node_game/transaction"
	_ "sanguo/node/node_game/user"
	"strconv"
	"strings"

	"github.com/go-ini/ini"
	"github.com/sniperHW/kendynet"
	"github.com/sniperHW/kendynet/golog"
)

func main() {

	if len(os.Args) < 2 {
		fmt.Printf("usage ./node_game config\n")
		return
	}

	golog.DisableStdOut()
	outLogger := golog.NewOutputLogger("log", "node_game", 1024*1024*50)
	kendynet.InitLogger(outLogger, "node_game")
	cluster.InitLogger(outLogger, "node_game")

	node_game.InitLogger(outLogger, "node_game")

	cfg, err := ini.LooseLoad(os.Args[1])
	if err != nil {
		node_game.Errorf("load %s failed:%s\n", os.Args[1], err.Error())
		return
	}

	secCommon := cfg.Section("Common")
	if nil == secCommon {
		node_game.Errorf("missing sec[Common]\n")
		return
	}

	sec := cfg.Section(os.Args[2])
	if nil == sec {
		node_game.Errorf("missing sec[%s]\n", os.Args[2])
		return
	}

	secTeam := cfg.Section("Team")
	if nil == sec {
		node_game.Errorf("missing sec[Team]\n")
		return
	}

	centerAddr := secCommon.Key("centerAddr").Value()
	clusterAddr := sec.Key("clusterAddr").Value()
	externalAddr := sec.Key("externalAddr").Value()
	redisAddr := secCommon.Key("redisAddr").Value()
	areaID := secCommon.Key("areaID").Value()
	serverID := sec.Key("serverID").Value()
	dirCenter := sec.Key("dirCenter").Value()
	teamAddr := secTeam.Key("clusterAddr").Value()

	t := strings.Split(clusterAddr, ":")
	ip := t[0]
	port, _ := strconv.Atoi(t[1])

	areaID_, _ := strconv.Atoi(areaID)

	serverID_, _ := strconv.Atoi(serverID)

	if 0 >= areaID_ {
		node_game.Errorf("node_game start failed invaild areaID:%s\n", areaID)
		return
	}

	asynwrap.Init(cluster.GetEventQueue())

	if !IDGen.Init(uint16(areaID_), byte(serverID_)) {
		node_game.Errorf("role init failed\n")
		return
	}

	centerAddrs := strings.Split(centerAddr, ",")
	if "" != dirCenter {
		centerAddrs = append(centerAddrs, dirCenter)
	}
	err = cluster.Start(centerAddrs, cluster.MakeService("game", ip, int32(port)))

	if nil != err {
		node_game.Errorf("node_game start failed1:%s\n", err.Error())
		return
	}

	db.RedisInit(strings.Split(redisAddr, ","))

	//moniter
	//moniter.Init()

	//Team服地址
	node_game.SetTeamServer(teamAddr)

	err = node_game.Start(uint16(areaID_), byte(serverID_), externalAddr)
	if nil != err {
		fmt.Printf("node_game start failed2:%s\n", err.Error())
	} else {
		fmt.Printf("node_game start on %s\n", externalAddr)
		node_game.ReportInit(cluster.MakeService("game", ip, int32(port)), externalAddr)
		sigStop := make(chan bool)
		_, _ = <-sigStop
	}
}
